@file:Suppress("DEPRECATION")
package com.juku2024.juku.tools
import android.app.Activity
import android.content.ComponentCallbacks
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Point
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.core.view.ViewCompat

/**
 * 屏幕操作相关的处理
 */
object ScreenUtils {

    /**
     * 隐藏底部虚拟按键, 会自动弹出来
     */
    private var systemUiVisibility: Int = 0
    fun hideBottomBar(activity: Activity, isFullScreen: Boolean) {
        try {
            //for new api versions.
            val decorView = activity.window.decorView
            //隐藏虚拟按键，并且全屏
            val uiOptions = if (isFullScreen) {
                systemUiVisibility = decorView.systemUiVisibility
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            } else {
                systemUiVisibility
            }
            if (uiOptions != 0) {
                decorView.systemUiVisibility = uiOptions
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 防止按home退出后，再次进入app的时候重新启动
     */
    fun ignoreHomeLauncher(activity: Activity): Boolean {
        try {
            if (!activity.isTaskRoot) {
                val intent = activity.intent
                val action = intent.action
                if (action != null && intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                    activity.finish()
                    return true
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 设置状态栏透明
     */
    @Suppress("DEPRECATION")
    fun setTranslucentSysBar(activity: Activity) {
        try {
            // 经测试在代码里直接声明透明状态栏更有效
            val mContentView = activity.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT)
            // 首先使 ChildView 不预留空间
            val mChildView: View? = mContentView.getChildAt(0)
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows(mChildView, false)
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 设置状态栏黑字白底
     */
    fun lightStatusBar(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val decorView = activity.window.decorView
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
    }


    private var finalScaledDensity: Float = 0.toFloat()
    private var finalDensity: Float = 0.toFloat()
    private var finalDensityDpi: Int = 0

    fun adaptScreen(context: Context, resources: Resources?, sizeInPx: Int): Resources? {
        if (resources == null || sizeInPx <= 0)
            return resources
        try {
            val systemDm = resources.displayMetrics
            if (finalScaledDensity == 0f && finalDensity == 0f && finalDensityDpi == 0) {
                val isVerticalSlide = isScreenVertical(resources)
                finalDensity = if (isVerticalSlide) {
                    systemDm.widthPixels / sizeInPx.toFloat()
                } else {
                    systemDm.heightPixels / sizeInPx.toFloat()
                }
                finalScaledDensity = finalDensity * (systemDm.scaledDensity / systemDm.density)
                finalDensityDpi = (160 * finalDensity).toInt()

                context.applicationContext.unregisterComponentCallbacks(object : ComponentCallbacks {
                    override fun onConfigurationChanged(newConfig: Configuration) {
                        systemDm.scaledDensity = context.applicationContext.resources.displayMetrics.scaledDensity
                    }

                    override fun onLowMemory() {
                    }
                })

                systemDm.density = finalDensity
                systemDm.scaledDensity = finalScaledDensity
                systemDm.densityDpi = finalDensityDpi
            } else {
                systemDm.density = finalDensity
                systemDm.scaledDensity = finalScaledDensity
                systemDm.densityDpi = finalDensityDpi
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return resources
    }


    /**
     * 获取状态栏高度（系统默认的）
     *
     * @return
     */
    fun getStatusBarHeight(): Int {
        val resources = Resources.getSystem()
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }

    fun displayScreenLog(activity: Activity) {
        val appDisplayMetrics = activity.resources.displayMetrics
        val log =
            "width: " + appDisplayMetrics.widthPixels + "\n" + "height: " + appDisplayMetrics.heightPixels + "\n" + "density: " + appDisplayMetrics.density + "\n" + "densityDpi: " + appDisplayMetrics.densityDpi
        Log.e("screen", log)
    }


    /**
     * Cancel adapt the screen.
     */
    fun cancelAdaptScreen(activity: Activity) {
        try {
            val systemDm = Resources.getSystem().displayMetrics
            val appDm = activity.application.resources.displayMetrics
            val activityDm = activity.resources.displayMetrics
            activityDm.density = systemDm.density
            activityDm.scaledDensity = systemDm.scaledDensity
            activityDm.densityDpi = systemDm.densityDpi
            appDm.density = systemDm.density
            appDm.scaledDensity = systemDm.scaledDensity
            appDm.densityDpi = systemDm.densityDpi
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


    fun getScreenSize(context: Context): IntArray {
        val wm = AppUtils.findActivity(context)?.windowManager!!
        val point = Point()
        wm.defaultDisplay.getSize(point)
        val width = point.x
        val height = point.y

        val size = IntArray(2)
        size[0] = width
        size[1] = height


//        val dm = context.resources.displayMetrics
//        size[0] = dm.heightPixels
//        size[1] = dm.widthPixels
        return size
    }


    /**
     * 获取当前activity的屏幕方向  默认竖直方向
     *
     * @param resources
     * @return
     */
    private fun isScreenVertical(resources: Resources?): Boolean {
        // 默认竖直方向
        var isScreenVertical = true
        if (resources != null) {
            val configuration = resources.configuration
            if (configuration != null) {
                isScreenVertical = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
            }
        }
        return isScreenVertical
    }
}